var uname = "";
var aes;
var md5_old = "";
var get_lock = false, send_lock = false;

$(document).ready(reset);

/**
 * 初始化函数
 * 
 * 包括jQuery事件的绑定等
 * @return void
 */
function reset() {
    uname = window.atob(getCookie("uname_base64"));
    aes_key = localStorage.getItem("aes_key");
    $("#send").click(send);
    $("#refresh").click(get);
    $("#loginout").click(loginout);
    $("#ico").attr("alt", uname);
    $("#ico").attr("src", "./static/images/" + uname + ".png");
    fnDate();
    setInterval(fnDate, 10000);
    get();
    setInterval(get, 5000);
}

function dealFail(reason) {
    console.log(reason);
}

/**
 * 检查AJAX请求是否成功，并做错误处理
 * 
 * 对请求失败进行分类处理
 * @param {string} data
 * @param {string} status
 * @return {Boolean} 是否该终止本次交互
 */
function IsQuit(data, status) {
    if (status !== "success") { //网络层面 的请求失败
        console.log("连接服务器失败");
        return true;
    }

    var response;
    try {
        response = $.parseJSON(data);
    }
    catch (e) {
        console.log("无法解析服务器响应(JSON解码失败)");
        return true;
    }

    if (response.status === "success")
        return false;

    //以下处理 服务器层面 的请求失败
    if (response.status === "fail") { //服务器返回了失败原因
        var reason = response.reason;
        dealFail(reason);
    } else if (response.status === "error") { //服务器没有返回失败原因
        console.log("服务器内部错误");
    } else { //无法识别
        console.log("无法解析服务器响应(JSON解码成功,但参数无法识别)");
    }
    return true;
}

/**
 * 更新聊天记录-第一步
 * 
 * 发送获取MD5请求
 * @return getS2
 */
function get() {
    if (get_lock === true)
        return;
    get_lock = true;
    $.post("./api.php",
        {
            action: "getmsgmd5"
        }, getS2);
}

/**
 * 更新聊天记录-第二步
 * 
 * 处理获取MD5请求，发送获取聊天记录请求
 * @return getS3
 */
function getS2(data, status) {
    if (IsQuit(data, status)) {
        get_lock = false;
        return;
    }
    var response = $.parseJSON(data);
    var md5_new = response.context;
    if (md5_new === md5_old) { //未产生新的聊天记录
        get_lock = false;
        return;
    }
    $.post("./api.php",
        {
            action: "getmsg"
        }, getS3);
}

/**
 * 更新聊天记录-第三步
 * 
 * 处理获取聊天记录请求
 * @return void
 */
function getS3(data, status) {
    if (IsQuit(data, status)) {
        get_lock = false;
        return;
    }
    var response = $.parseJSON(data);
    var record_encrypt = response.context;
    var record = decrypt(record_encrypt, aes_key);
    md5_old = md5(record);
    loadRecord(record);
    get_lock = false;
}

/**
 * 加载聊天记录
 * 
 * 把AJAX获取到的聊天记录加载至页面
 * @param {string} record
 * @return void 
 */
function loadRecord(record) {
    $("#context").empty();
    var list = record.split("\r\n");
    for (var i = 0; i < list.length - 1; i++) {
        var item = $.parseJSON(list[i]);
        var line = `<li>${item.time} ${item.uname}(${item.ip})`;
        line += `<img src=\"./static/images/${item.uname}.png\" alt=\"${item.uname}\" `;
        if (item.uname === uname)
            line += "class=\"imgright\"><span class=\"spanright\">";
        else
            line += "class=\"imgleft\"><span class=\"spanleft\">";
        line += `${decodeURI(item.msg)}</span></li>\r\n`;
        $("#context").append(line);
    }
    $("#context").scrollTop($("#context").prop("scrollHeight")); //内容过多时，将滚动条放置到最底端
}

/**
 * 发送信息-第一步
 * 
 * 计算信息的AES加密值，AJAX提交
 * @return sendS2 
 */
function send() {
    if (send_lock === true)
        return;
    send_lock = true;
    var msg = $("#msg").val();
    if (msg === "") {
        send_lock = false;
        return;
    }
    msg = encodeURI(msg); //URL编码，防止中文不兼容的情况
    var msg_encrypt = encrypt(msg, aes_key);
    var msg_md5 = md5(msg);
    $.post("./api.php",
        {
            action: "sendmsg",
            msg: msg_encrypt,
            md5: msg_md5
        }, sendS2);
}

/**
 * 发送信息-第二步
 * 
 * 处理提交结果
 * @return void 
 */
function sendS2(data, status) {
    if (IsQuit(data, status)) {
        send_lock = false;
        return;
    }
    $("#msg").val("");
    send_lock = false;
    get();
}

/**
 * 退出登录-第一步
 * 
 * 发送退出登录请求
 * @return loginoutS2
 */
function loginout() {
    $.post("./api.php",
        {
            action: "loginout",
        }, loginoutS2);
}

/**
 * 退出登录-第二步
 * 
 * 处理退出登录请求
 * @return void
 */
function loginoutS2(data, status) {
    if (IsQuit(data, status)) {
        return;
    }
    location.replace(location.href);
}

/**
 * 更新时间函数
 * 
 * 无简介
 * @return void
 */
function fnDate() {
    var date = new Date();
    var hours = date.getHours();
    var minutes = date.getMinutes();
    var time = fnW(hours) + ":" + fnW(minutes);
    $("#time").html(time);
}
function fnW(str) {
    var num;
    str > 9 ? num = str : num = "0" + str;
    return num;
}

document.onkeydown = function(event) {
    var e = event || window.event || arguments.callee.caller.arguments[0];
    if (e && e.keyCode == 27) { //Esc 
        loginout();
    }
    if (e && e.keyCode == 113) { //F2 
        get();
    }
    if (e && e.keyCode == 13) { //enter
        send();
    }
}
